package com.example.stag;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.ResultSet;

@WebServlet("/resetPassword")
public class ResetPasswordServlet extends HttpServlet {

    @Override
    public void init() {
        UserSQLOperation.connect();
        CommoditySQLOperation.connect();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        UserSQLOperation.connect();
        CommoditySQLOperation.connect();
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");
        try {
            PrintWriter writer = resp.getWriter();
            String username = req.getParameter("username");
//            String oldPassword = req.getParameter("oldPassword");
            String newPassword = req.getParameter("newPassword");
            String usertype = req.getParameter("usertype");

            //
            ResultSet resultSet = UserSQLOperation.searchByUsername(username);
            if (!resultSet.next()) {
                writer.println("user not exist");
            } else {
                do {
                    // 循环判断，如果有匹配的则返回ok
                    if (resultSet.getString("usertype").equals(usertype)) {
                        UserSQLOperation.updatePassword(username, newPassword, usertype);
                        writer.println("OK");
                        return;
                    }
                } while (resultSet.next());
                writer.println("wrong");
            }


            // 如果一开始就不存在结果集，则代表用户不存在
//            if (!resultSet.next()) {
//                writer.println("user not exist");
//            } else {
//                do {
//                    // 循环判断，如果有匹配的则返回ok
//                    if (resultSet.getString("password").equals(oldPassword) && resultSet.getString("usertype").equals(usertype)) {
//                        UserSQLOperation.updatePassword(username, newPassword, usertype);
//                        writer.println("OK");
//                        return;
//                    }
//                } while (resultSet.next());
//                writer.println("wrong");
//            }
//
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
